$(function () {
    $("#jqGrid").Grid({
        url: '../toolspartin/list',
        colModel: [
            {label: 'id', name: 'id', index: 'ID', key: true, hidden: true},
            {label: '入库单号', name: 'inCode', index: 'IN_CODE', width: 130},
            {label: '工装名称', name: 'name', index: 'tb.name', width: 80},
            {label: '型号规格', name: 'spec', index: 'tb.type', width: 80},
            {label: '工装编码', name: 'partCode', index: 'PART_CODE', width: 80,frozen: true},
            {label: '图号', name: 'mapNo', index: 'MAP_NO', width: 120,frozen: true},
            {label: '入库仓库', name: 'intStoreName', index: 'SH.NAME', width: 120},
            {label: '货位', name: 'cargoLocationName', index: 'CARGO_LOCATION', width: 80},
            {
                label: '入库日期', name: 'inDate', index: 'IN_DATE', width: 80, formatter: function (value) {
                    return transDate(value, 'yyyy-MM-dd');
                }
            },
            {label: '入库数量', name: 'inNum', index: 'IN_NUM', width: 60},
            {
                label: '入库时间', name: 'createDate', index: 'CREATE_DATE', width: 80, formatter: function (value) {
                    return transDate(value, 'yyyy-MM-dd hh:mm');
                }
            },
            {
                label: '来源', name: 'resources', index: 'RESOURCES', width: 60, formatter: function (value) {
                    var res= sysEnums.SPARE_RESOURCES_TYPE[value];
                    if(!res){
                        res="未知";
                    }
                    return res;
                }
            },
            {label: '备注', name: 'remark', sortable: false, width: 80},
        ]
    });
});

var vm = new Vue({
    el: '#rrapp',
    data: {
        showList: true,
        cargoLocation:true,
        cargoLocationName:false,
        title: null,
        toolsPartIn: {
            partCode: '', // 工装编码
            name: '',// 工装名称
            type: '', // 工装型号规格
            mapNo: '', // 图号
            createNo: '',// 自制图号
            toolsId: '', // 工装ID
            inStoreId: '', // 工装仓库ID

            intStore: '', // 工装仓库编码
            cargoLocation: '', // 工装库位ID
            cargoLocationName: '', // 工装库位名称



            remark: '',
            operationName: '',
            operation: '',
            procUse: '',
            useDevId: '',
            useDevName: '',
            useDevCode: '',
            inNum: '',
            partPrice: '',
            partUnit: '',
            spec: '',
            name: '',
            partCode: '',
            cargoLocation: '',

            useUnit: '',
            inDate: '',
            inCode: '',
            resources: '',
            id: '',
        },
        ruleValidate: {
            partCode: [
                {required: true, message: '工装必选', trigger: 'blur'}
            ],
            inNum: [
                {required: true, message: '入库数量不能为空', trigger: 'blur'}
            ],
            name: [
                {required: true, message: '工装必选', trigger: 'change'}
            ]
        },
        q: {
            name: '', // 名称
            mapNo: '', // 图号
            type: '', // 型号规格
            beginTime:'', // 开始时间
            endTime:'' // 结束时间
        },
        //货位ID，如果货位ID为空，则后台自动添加数据保存
        hwID:'',
        optionList:'',//货位列表，实时查询
        storeId:'', //仓库ID
        storeName:'',//仓库名字
        flag:'', //是否新增库位判断标识 1:新增 0:现有
        sourceList: enumsToList('TOOLS_RESOURCES_TYPE'),
        transitNum: 0, // 关联需求计划详情，展示用
        planItemDesc: '', // 关联需求计划明细描述 格式：
        partPrice: '', // 入库备件价格
        isDisabled: false // 控制入库按钮
    },
    methods: {
        query: function () {
            vm.reload();
        },
        add: function () {
            vm.showList = false;
            vm.title = "新增";
            vm.storeName = '';
            vm.planItemDesc = '';
            vm.transitNum = '';
            vm.toolsPartIn = {
                remark: '',
                operationName: '',
                operation: '',
                procUse: '',
                useDevId: '',
                useDevName: '',
                useDevCode: '',
                inNum: '',
                partPrice: '',
                partUnit: '',
                spec: '',
                name: '',
                partCode: '',
                cargoLocation: '',
                cargoLocationName: '',
                inStoreId: '',
                intStore: '',
                useUnit: '',
                inDate: '',
                inCode: '',
                resources: '',
                id: '',
                partNeedsItemId: '' // 关联备件需求计划详情ID
            };
            vm.showLoc(1);
            vm.flag=0;
        },
        saveOrUpdate: function (event) {
            var url = vm.toolsPartIn.id == (null || '') ? "../toolspartin/save" : "../toolspartin/update";
            /*
                工装库位有两种：选择现有库位(flag=1)和新增库位(flag=0)
                需要针对不同场景做必填校验
             */
            var cargoLocationName = vm.toolsPartIn.cargoLocationName;
            if(vm.flag==1){
                // 手动输入库位
                vm.toolsPartIn.cargoLocation="";
                if(!cargoLocationName || cargoLocationName.length==0){
                    alert("备件存放位置不能为空！");
                    return;
                }
            }else if(vm.flag == 0){
                // 手动选择现有库位
                if(!vm.toolsPartIn.cargoLocation){
                    alert("货位必选！");
                    return;
                }
            }

            // 校验来源
            if(vm.toolsPartIn.resources == 4) {
                // 关联计划必填
                if(!vm.toolsPartIn.partNeedsItemId){
                    iview.Message.error("工装来源为[需求计划]时，关联计划必选！");
                    return;
                }
                // 入库数量不得大于需求在途数 校验
                let transitNumIn = parseInt(vm.transitNum);
                let inNum = parseInt(vm.toolsPartIn.inNum);
                if(transitNumIn < inNum){
                    iview.Message.error("入库数量不得大于需求在途数！");
                    return;
                }
            }
            // 禁用提交按钮，防止重复提交
            if(vm.isDisabled){
                iview.Message.error("备件入库处理中，请勿重复点击！");
                return;
            }
            this.$Loading.start();
            vm.isDisabled = true;
            Ajax.request({
                url: url,
                params: JSON.stringify(vm.toolsPartIn),
                type: "POST",
                contentType: "application/json",
                successCallback: function (r) {
                    alert('入库成功', function (index) {
                        vm.isDisabled = false;
                        vm.$Loading.finish();
                        vm.reload();
                    });
                }
            });
        },
        del: function (event) {
            var ids = getSelectedRows("#jqGrid");
            if (ids == null) {
                return;
            }

            confirm('确定要删除选中的记录？', function () {
                Ajax.request({
                    url: "../toolspartin/delete",
                    params: JSON.stringify(ids),
                    type: "POST",
                    contentType: "application/json",
                    successCallback: function () {
                        alert('操作成功', function (index) {
                            vm.reload();
                        });
                    }
                });
            });
        },
        getInfo: function (id) {
            Ajax.request({
                url: "../toolsPartIn/info/" + id,
                async: true,
                successCallback: function (r) {
                    vm.toolsPartIn = r.toolsPartIn;
                }
            });
        },
        reload: function (event) {
            vm.showList = true;
            let param = {};
            if(vm.q.name){
                param.name = vm.q.name;
            }
            if(vm.q.mapNo){
                param.mapNo = vm.q.mapNo;
            }
            if(vm.q.type){
                param.type = vm.q.type;
            }
            if(vm.q.beginTime){
                param.beginTime = gmt2DateStr(vm.q.beginTime);
            }
            if(vm.q.endTime){
                param.endTime = gmt2DateStr(vm.q.endTime);
            }
            // 清空postData缓存数据

            var postData = $("#jqGrid").jqGrid("getGridParam", "postData");
            $.each(postData, function (k, v) {
                delete postData[k];
            });
            // 获取当前分页信息
            var page = $("#jqGrid").jqGrid('getGridParam', 'page');
            $("#jqGrid").jqGrid('setGridParam', {
                postData: param,
                page: page
            }).trigger("reloadGrid");
        },
        // 获取工装在仓库中的库位列表
        getStorePos: function () {
            Ajax.request({
                url: "../toolsstorepos/queryAll",
                params: {"storeId": vm.toolsPartIn.inStoreId ,"toolsCode":vm.toolsPartIn.partCode},
                async: true,
                successCallback: function (r) {
                    vm.optionList = r.list;
                }
            });
        },
        reloadSearch: function () {
            vm.q = {
                name: '', // 名称
                mapNo: '', // 图号
                type: '', // 型号规格
                beginTime:'', // 开始时间
                endTime:'' // 结束时间
            };
            vm.reload();
        },
        handleSubmit: function (name) {
            handleSubmitValidate(this, name, function () {
                vm.saveOrUpdate()
            });
        },
        handleReset: function (name) {
            handleResetForm(this, name);
        },
        selectTools: function () {
            openWindow({
                type: 2,
                title: '<i class="fa fa-file-text-o"></i> 选择工装',
                content: '../tools/toolslistSelect.html',
                btn: ['确定', '取消'],
                btn1: function (index) {
                    var iframeWin = window["layui-layer-iframe" + index];
                    var res = iframeWin.getTools();
                    if (!res) {
                        iview.Message.error("请选择一条记录");
                    } else {
                        layer.close(index);
                        vm.toolsPartIn.partCode = res.toolsCode;
                        vm.toolsPartIn.name = res.name;
                        vm.toolsPartIn.type = res.type;
                        vm.toolsPartIn.mapNo = res.mapNo;
                        vm.toolsPartIn.createNo = res.createNo;
                        vm.toolsPartIn.toolsId = res.id;
                    }
                }
            })
        },
        relateNeedsPlanDetail: function () {
            if(!vm.toolsPartIn.partCode){
                iview.Message.error("请先选择入库备件！");
                return;
            }
            openWindow({
                type: 2,
                title: '<i class="fa fa-file-text-o"></i> 选择备件需求计划明细',
                content: '../spare/sparePartNeedsPlanDetailRelate.html?sparePartCode=' + vm.toolsPartIn.partCode,
                btn: ['确定', '取消'],
                btn1: function (index) {
                    var iframeWin = window["layui-layer-iframe" + index];
                    var res = iframeWin.getSparePart();
                    if (!res) {
                        iview.Message.error("请选择一条记录");
                    } else {
                        layer.close(index);
                        vm.toolsPartIn.partNeedsItemId = res.id;
                        vm.transitNum = res.transitNum;
                        vm.planItemDesc = res.businessCode + ' ' + res.materialName + ' ' + res.spec;
                        vm.partPrice = res.planPrice;
                    }
                }
            })
        },
        //选择入库仓库
        getStoreHouse: function () {
            if(!vm.toolsPartIn.partCode){
                alert("请先选择入库的备件，在选择仓库");
                return;
            }else {
                openWindow({
                    type: 2,
                    title: '<i class="fa fa-institution"></i> 选择仓库',
                    content: '../sys/storeHouseSelect.html?type=2',
                    btn: ['确定', '取消'],
                    btn1: function (index) {
                        var iframeWin = window["layui-layer-iframe" + index];
                        var res = iframeWin.getStoreHouse();
                        if (!res) {
                            iview.Message.error("请选择一条记录");
                        } else {
                            layer.close(index);
                            vm.toolsPartIn.intStore = res.storeCode;
                            vm.toolsPartIn.inStoreId = res.id;
                            vm.storeName = res.name;
                            //获取位置列表
                            vm.getStorePos();
                        }
                    }
                })
            }
        },
        showLoc:function (type) {
            if(type==0){
                // 手动输入库位
                vm.cargoLocation = false;
                vm.cargoLocationName= true;
                vm.toolsPartIn.cargoLocationName="";
                vm.flag = 1;
            }else if(type==1){
                // 从现有库位中选择
                vm.cargoLocation = true;
                vm.cargoLocationName= false;
                vm.toolsPartIn.cargoLocation="";
                vm.flag =0;
            }
        }
    }
});
